08. Argument Matchers
Argument Matchers
ND079 JPND C3 L5 A06 Argument Matchers V3
Mocking Variable Input
Our previous example returned a specific input when fizzBuzz
was called with a value of 1.
when(salesService.fizzBuzz(1)).thenReturn(input);
You can use the ArgumentMatchers
class to accept variable input instead. For example, ArgumentMatchers.anyInt()
accepts any integer value.
@Test
public void fancyBusiness_getsEvenNumber_returnsBaz() {
when(salesService.fizzBuzz(anyInt())).thenReturn("2");
// verify that no matter what number we pass into fancyBusiness,
// we'll return "Baz" if fizzbuzz yields an even number
for(int i = 0; i < 100; i++) {
Assertions.assertEquals("Baz", userService.fancyBusiness(i));
}
}
Types of ArgumentMatchers
Type Matchers:
- Primitives: anyInt(), anyFloat(), anyBoolean(), etc.
- Objects: any(), any(Class
) - Collections: anyCollection(), anyIterable(), anyList(), anyMap(), anySet()
Value Matchers:
- Primitives: eq(val)
- Objects: eq(obj), same(obj), refEq(obj)